package com.hankol.winecellar.utils

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Point
import android.os.*
import android.view.LayoutInflater
import android.view.View
import android.widget.Toast
import androidx.annotation.NonNull
import androidx.appcompat.app.AppCompatActivity
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.CoordType
import com.baidu.mapapi.SDKInitializer
import com.baidu.mapapi.map.BaiduMap
import com.baidu.mapapi.map.InfoWindow
import com.baidu.mapapi.map.MapStatus
import com.baidu.mapapi.map.MapStatusUpdateFactory
import com.baidu.mapapi.model.LatLng
import com.baidu.mapapi.model.LatLngBounds
/*import com.baidu.navisdk.adapter.BNRoutePlanNode
import com.baidu.navisdk.adapter.BaiduNaviManagerFactory
import com.baidu.navisdk.adapter.IBNRoutePlanManager
import com.baidu.navisdk.adapter.IBaiduNaviManager.INaviInitListener
import com.baidu.navisdk.adapter.struct.BNTTsInitConfig*/
import com.baselibrary.activity.BaseActivity
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.load
import com.baselibrary.extension.toast
import com.baselibrary.manager.LoadingManager
import com.baselibrary.utils.ContextUtils
import com.baselibrary.utils.HKLogUtils
import com.baselibrary.utils.SpUtils
import com.baselibrary.view.CircleImageView
import com.hankol.winecellar.R
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream


object BaiduMapUtils {

    interface ICallBack {
        fun onClick4Pos()
    }

    /**
     * 某个点居中显示在地图
     */
    fun clickPositionCenter(mBaiduMap: BaiduMap, pos: LatLng, isScale: Boolean = true) {
        val builder = LatLngBounds.Builder()
        val latitude = SpUtils.getFloat(ContextUtils.getCurApplication().applicationContext, "address_Lat", 0f)
        val longitude = SpUtils.getFloat(ContextUtils.getCurApplication().applicationContext, "address_long", 0f)
        if (isScale) {//是否需要缩放，点击地图的点的时候不让缩放
            builder.include(LatLng(latitude.toDouble(), longitude.toDouble())) //我的位置
            builder.include(pos) //设备点
            val z = MapStatusUpdateFactory.newLatLngBounds(builder.build())
            mBaiduMap.animateMapStatus(z)
            val mapStatusUpdate = MapStatusUpdateFactory.zoomBy(-2f)
            mBaiduMap.animateMapStatus(mapStatusUpdate)
        }
        val u = MapStatusUpdateFactory.newLatLng(pos)//使输入的点位于地图中心
        mBaiduMap.animateMapStatus(u)
    }

    /**
     * 在某个点上显示气泡
     */
    fun clickPositionShowPop(act: Activity, mBaiduMap: BaiduMap, pos: LatLng, coverUrl: String, callback: ICallBack?) {
        //创建InfoWindow展示的view
//        val pointView = layoutInflater.inflate(R.layout.pop_point_img, null, false)
        val pointView = LayoutInflater.from(act).inflate(R.layout.pop_point_img,null)
        pointView.findViewById<CircleImageView>(R.id.img_dot).load(act, coverUrl)
        pointView.findViewById<CircleImageView>(R.id.img_dot).setOnClickListener {
            if (callback.checkNotNull()) {
                callback?.onClick4Pos()
            }
        }
        //定义用于显示该InfoWindow的坐标点
        //创建InfoWindow , 传入 view， 地理坐标， y 轴偏移量
        val mInfoWindow = InfoWindow(pointView, pos, -47);
        //显示InfoWindow
        mBaiduMap.showInfoWindow(mInfoWindow);
    }

    fun initNav(mContext: BaseActivity, sLongitude: Double, sLatitude: Double, sName: String, dLongitude: Double, dLatitude: Double, dName: String) {
       /* LoadingManager.showLoadingDialog(mContext)
        BaiduNaviManagerFactory.getBaiduNaviManager().init(mContext, mContext.getExternalFilesDir(null).getPath(), "hankolNav", object : INaviInitListener {
            override fun onAuthResult(status: Int, msg: String) {
                var authinfo = ""
                if (0 == status) {
//                    authinfo = "key校验成功!"
                } else {
//                    authinfo = "key校验失败, $msg"
                }
//                mContext.runOnUiThread(Runnable { Toast.makeText(mContext, authinfo, Toast.LENGTH_LONG).show() })
            }

            override fun initStart() {
//                Toast.makeText(mContext, "百度导航引擎初始化开始", Toast.LENGTH_SHORT).show()
            }

            override fun initSuccess() {
//                Toast.makeText(mContext, "百度导航引擎初始化成功", Toast.LENGTH_SHORT).show()
                // 初始化tts
                if (sLongitude == 0.0 && sLatitude == 0.0) {
                    val currentLatitude = SpUtils.getFloat(ContextUtils.getCurApplication().applicationContext, "address_Lat", 0f)
                    val currentLongitude = SpUtils.getFloat(ContextUtils.getCurApplication().applicationContext, "address_long", 0f)
                    openNav(mContext, currentLongitude.toDouble(), currentLatitude.toDouble(), sName, dLongitude, dLatitude, dName)
                } else {
                    openNav(mContext, sLongitude, sLatitude, sName, dLongitude, dLatitude, dName)
                }
            }

            override fun initFailed(errCode: Int) {
                Toast.makeText(mContext, "百度导航引擎初始化失败${errCode}", Toast.LENGTH_SHORT).show()
            }
        })*/
    }

    fun openNav(mContext: AppCompatActivity, sLongitude: Double, sLatitude: Double, sName: String, dLongitude: Double, dLatitude: Double, dName: String) {
/*
        SDKInitializer.setAgreePrivacy(mContext.applicationContext, true)
        SDKInitializer.setCoordType(CoordType.GCJ02)
        SDKInitializer.initialize(mContext.applicationContext)
        initTTS(mContext)
        val list: MutableList<BNRoutePlanNode> = ArrayList()
        val startNode = BNRoutePlanNode.Builder().latitude(sLatitude).longitude(sLongitude).name(sName).description(sName).build()
        val endNode = BNRoutePlanNode.Builder().latitude(dLatitude).longitude(dLongitude).name(dName).description(dName).build()
        list.add(startNode)
        list.add(endNode)
        // 关闭电子狗
        if (BaiduNaviManagerFactory.getCruiserManager().isCruiserStarted) {
            BaiduNaviManagerFactory.getCruiserManager().stopCruise()
        }
        BaiduNaviManagerFactory.getRoutePlanManager().routePlanToNavi(list, IBNRoutePlanManager.RoutePlanPreference.ROUTE_PLAN_PREFERENCE_DEFAULT, Bundle(), object : Handler(Looper.getMainLooper()) {
            override fun handleMessage(@NonNull msg: Message) {
                when (msg.what) {
                    IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_START -> {
//                        Toast.makeText(mContext, "算路开始", Toast.LENGTH_SHORT).show()
                    }
                    IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_SUCCESS -> {
//                        Toast.makeText(mContext, "算路成功", Toast.LENGTH_SHORT).show()

                    }
                    IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_FAILED -> {
                        "算路失败".toast()
                    }
                    IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_TO_NAVI -> {
                        LoadingManager.hideLoadingDialog(mContext)
//                        Toast.makeText(mContext.getApplicationContext(), "算路成功准备进入导航", Toast.LENGTH_SHORT).show()
                        val it = Intent(mContext, DemoGuideActivity::class.java)
                        it.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
                        mContext.startActivity(it)
                    }
                    else -> {
                    }
                }
            }
        })*/
    }

    fun getCustomStyleFilePath(context: Context, customStyleFileName: String): String {
        var outputStream: FileOutputStream? = null
        var inputStream: InputStream? = null
        var parentPath: String? = null
        try {
            inputStream = context.assets.open("customConfigdir/$customStyleFileName")
            val buffer = ByteArray(inputStream.available())
            inputStream.read(buffer)
            parentPath = context.filesDir.absolutePath
            val customStyleFile = File("$parentPath/$customStyleFileName")
            if (customStyleFile.exists()) {
                customStyleFile.delete()
            }
            customStyleFile.createNewFile()
            outputStream = FileOutputStream(customStyleFile)
            outputStream.write(buffer)
        } catch (e: IOException) {
            HKLogUtils.e("个性化地图CustomMap", "Copy custom style file failed", e)
        } finally {
            try {
                inputStream?.close()
                if (outputStream != null) {
                    outputStream.close()
                }
            } catch (e: IOException) {
                HKLogUtils.e("个性化地图CustomMap", "Close stream failed", e)
                return ""
            }
        }
        return "$parentPath/$customStyleFileName"
    }

    private fun initTTS(mContext: Context) {
        // 使用内置TTS
//        val config = BNTTsInitConfig.Builder().context(mContext).sdcardRootPath(getSdcardDir(mContext)).appFolderName("hankolNav").appId("26435605").appKey("Fw6w7r0HijCB3xEvLAMZ8laaWtATZAzU").authSn("95a66d8c-80620c6f-01-0197-007f-027c-01").build()
//        BaiduNaviManagerFactory.getTTSManager().initTTS(config)
    }

    private fun getSdcardDir(mContext: Context): String? {
        return if (Build.VERSION.SDK_INT >= 29) {
            // 如果外部储存可用 ,获得外部存储路径
            val file: File? = mContext.getExternalFilesDir(null)
            if (file != null && file.exists()) {
                file.path
            } else {
                mContext.getFilesDir().getPath()
            }
        } else {
            Environment.getExternalStorageDirectory().absolutePath
        }
    }

    /**请求定位，只在MainActivity处理
     * @author: merbng
     * @time: 2022/11/11 16:41
     * @description:
     */
    fun getLocationInfo(locationClient: LocationClient, bdAbstractLocationListener: BDAbstractLocationListener) {
        val option = LocationClientOption();
        option.locationMode = LocationClientOption.LocationMode.Hight_Accuracy;// 可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("gcj02");// 可选，默认gcj02，设置返回的定位结果坐标系
        //int span = 1000;
        option.setScanSpan(0);// 可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);// 可选，设置是否需要地址信息，默认不需要
        option.isOpenGps = true;// 可选，默认false,设置是否使用gps
        option.isLocationNotify = true;// 可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);// 可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);// 可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);// 可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);// 可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);// 可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        locationClient.locOption = option;
        locationClient.registerLocationListener(bdAbstractLocationListener)
        locationClient.start();
    }

    /**中心点偏移
     * @author: merbng
     * @time: 2022/11/11 16:42
     * @description: isSmallMap：true：小地图，
     */
    fun mapCenterPointUpdate(mBaiduMap: BaiduMap, isSmallMap: Boolean = true,v:View,v_pos_h:View) {
        val point = IntArray(2)
        (  if (isSmallMap) v else v_pos_h).getLocationOnScreen(point)
        val mapStatus = MapStatus.Builder().targetScreen(Point(point[0], point[1])).build()
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(mapStatus))
    }
}